package com.carbeauty.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.carbeauty.daoimpl.CarColorDaoImpl;
import com.carbeauty.image.Constants;
import com.carbeauty.web.listener.ImageIndexCreateListener;


public class FileUploadController extends MultiActionController{
	
	private CarColorDaoImpl carColorService;
	
    public CarColorDaoImpl getCarColorService() {
		return carColorService;
	}

	public void setCarColorService(CarColorDaoImpl carColorService) {
		this.carColorService = carColorService;
	}
	
	public ModelAndView goFileUpload(HttpServletRequest request,  
            HttpServletResponse response) throws ServletException, IOException {  

        String fileType = request.getParameter("fileType");  
        String maxSize = request.getParameter("maxSize");  
        ModelAndView mav = new ModelAndView();  
          
        
        if(fileType!=null && !"".equals(fileType.trim())){  
            mav.addObject("fileType", fileType);  
        }  
        if(maxSize!=null && !"".equals(maxSize.trim())){  
            mav.addObject("maxSize", maxSize);  
        }  
        mav.setViewName("pages/imageUpload");
        
        return mav;  
    } 
	
	private String[] fileUpload(HttpServletRequest request,HttpServletResponse response) throws Exception 
	{
		String realImageLocation="";
		String filePath = Constants.FILE_UPLOAD_TEMP_DIR+File.separator;//getServletContext().getRealPath("/")+"upload/";
		File file=new File(filePath);//上传文件保存位置
		File tempfile=new File( Constants.FILE_UPLOAD_TEMP_DIR+"2"+File.separator);//上传缓存临时文件夹
		if(!file.exists()){
		    file.mkdir();
		}
		if(!tempfile.exists()){
		    tempfile.mkdir();
		}
		
		String fileType = request.getParameter("fileType");  
        String maxSize = request.getParameter("maxSize");  
        
		DiskFileItemFactory factory = new DiskFileItemFactory();  
		//最大缓存  
		factory.setSizeThreshold(5*1024);  
		//设置临时文件目录  
		factory.setRepository(tempfile);  
		ServletFileUpload upload = new ServletFileUpload(factory);  
		if(maxSize!=null && !"".equals(maxSize.trim())){  
		   //文件最大上限  
		    upload.setSizeMax(Integer.valueOf(maxSize)*1024*1024);  
		}  
	    String fileName = "";
	    String fileNameRandom ="";
		    //获取所有文件列表  
		    List<FileItem> items = upload.parseRequest(request);  
		    for (FileItem item : items) {  
		        if(!item.isFormField()){  
		            //文件名  
		              fileName = item.getName();  
		            //检查文件后缀格式  
		            String fileEnd = fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();  
		            if(fileType!=null && !"".equals(fileType.trim())){  
		                boolean isRealType = false;  
		                String[] arrType = fileType.split(",");  
		                for (String str : arrType) {  
		                    if(fileEnd.equals(str.toLowerCase())){  
		                        isRealType = true;  
		                        break;  
		                    }  
		                }  
		                if(!isRealType){  
		                    //提示错误信息:文件格式不正确  
		                	PrintWriter out = response.getWriter();
		                	out.write("文件格式不正确!");
		                    return null;  
		                }  
		            }   
		            //创建文件唯一名称  
		              fileNameRandom = "Temp_"+UUID.randomUUID().toString()+"."+fileEnd;  
		            //真实上传路径  
		            StringBuffer sbRealPath = new StringBuffer();  
		            sbRealPath.append(filePath).append(fileNameRandom);  
		            //写入文件  
		            realImageLocation = sbRealPath.toString();
		            File realFile = new File(realImageLocation);  
		            item.write(realFile);  
		        }
		    }
		
		          return   new String[]{fileNameRandom,fileNameRandom};
	}
	
	public ModelAndView uploadFile(HttpServletRequest request,HttpServletResponse response)
		throws Exception{
		ModelAndView mav = new ModelAndView();
		 String fileNames[] = fileUpload(request,response);
         mav.addObject("isuploaded", "Y");
         mav.addObject("fileName", fileNames[0]);
         mav.addObject("realImageLocation", fileNames[1]);
         mav.setViewName("pages/imageUpload");
		return mav;
		
	}	

}
